<?php

class compose extends Controller {
	
	public function index($to='', $subject='') {
		$this->vars['to'] = $to;//str_replace(':', '@', $to);
		$this->vars['subject'] = $subject;
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$this->render('compose');
	}
	
	public function reply ( $mailbox, $uid, $to_all='no' )
	{
		$mailbox = Imap::chooseMailbox($mailbox);
		$email = Email::findEmailByUid($mailbox,$uid);
		$this->vars['to'] = $email->fromSimple;
		if ( $to_all == 'all' )
		{
			if ( strlen($email->toSimple)!=0)
				$this->vars['to'] .= ', ' . $email->toSimple;
			$this->vars['cc'] = $email->ccSimple;
		}
		$this->vars['subject'] = 'Re: ' . $email->subject;
		$this->vars['content'] = "\r\n\r\n";
		if(empty($email->htmlmsg))
			$this->vars['content'] .= Email::formatContentForReply($email->plainmsg);
		else
			$this->vars['content'] .= Email::formatContentForReply($email->htmlmsg);
		$this->render('compose');
	}
	
	public function draft ( $uid )
	{
		$mailbox = Imap::chooseMailbox(DRAFTS);
		$email = Email::findEmailByUid($mailbox,$uid);
		$this->vars['uid'] = $uid;
		$this->vars['to'] = $email->toSimple;
		$this->vars['cc'] = $email->ccSimple;
		$this->vars['bcc'] = $email->bccSimple;
		$this->vars['subject'] = $email->subject;
		if(empty($email->htmlmsg))
			$this->vars['content'] = $email->plainmsg;
		else
			$this->vars['content'] = $email->htmlmsg;
		$this->render('compose');
	}
	
	public function saveDraft ()
	{
		$res = '-1';
		//die($res . ' ' . $_POST['email']['uid']);//debug
		// Test si l'utilisateur est connecté
		if ( !User::isLogged() ) {
			//header('Location: '.WEB_ROOT.'member/index');
			die ( $res . ' Error: Not logged in.' );
		}
		// Test si des variables POST "compose" ont été envoyés
		if ( !isset($_POST['email']) || !isset($_POST['email']['uid']) ) {
			//header('Location: '.WEB_ROOT.'compose/index');
			die ( $res . ' Error: No input data.' );
		}
		//echo 'a';
		$_SESSION['email'] = $_POST['email'];
		extract($_POST['email']);
		
		$mailbox = Imap::chooseMailbox(DRAFTS);
		$m = Imap::open($mailbox);
		
		// supprimer le brouillon
		if ( $uid != -1 )
		{
			imap_delete($m, imap_msgno($m,$uid));
			imap_expunge($m);
		}
		//echo 'b';
		
		// récupérer la valeur du prochain uid qui sera créé
		$mc = imap_status ( $m, Imap::$hostname . $mailbox, SA_UIDNEXT );
		if ( !$mc )
		{
			Imap::close ( $m );
			die($res . ' could not check emails');
		}
		$next = $mc->uidnext;
		
		
		
		// sauvegarder le nouveau brouillon
		
		$envelope["to"] = $to;
		$envelope["cc"] = $cc;
		$envelope["bcc"] = $bcc;
		$from = $_SESSION['user']['username'].'@'.EMAILDOMAIN;
		$envelope["from"] = $from;
		$envelope["subject"]  = $subject;
		$envelope["date"]  = date("r", strtotime("now"));

		$part["type"] = TYPETEXT;
		$part["subtype"] = "plain";
		//$part["description"] = "part description";
		$part["contents.data"] = $content;
		//echo 'c';
		$body[1] = $part;
		$msg = imap_mail_compose ( $envelope, $body );
		if ( imap_append ( $m, Imap::$hostname . $mailbox, $msg ) === false ) {
			$msg = $res . ' could not append message: ' . imap_last_error ();
			Imap::close ( $m );
			die ( $msg );
		}
		imap_setflag_full($m, imap_msgno($m,$next), "\\Seen");
		//echo 'd';
		
		/*$result = imap_fetch_overview($m,'1:'.$mc->Nmsgs,FT_UID); // TODO: numero de msg != Nmsgs (si des msgs ont été suppr)
		$res = -1;
		foreach ( $result as $v )
		{
			echo 'uid:' . $v->uid . ';';
			print_r($v);
			if ( isset($v->uid) && $v->uid > $n )
			{
				$res = $v->uid;
			}
		}
		echo $res;
		//if ( !empty($result) && count($result) != 0 && isset($result[0]->uid) )
			//$res = $result[0]->uid;
			//print_r($result);
		//echo 'f';*/
		Imap::close ( $m );
		$res = $next;
		echo $res;
		exit;
		
	}
	
	public function forward ( $mailbox, $uid )
	{
		$mailbox = Imap::chooseMailbox($mailbox);
		$email = Email::findEmailByUid($mailbox,$uid);
		$this->vars['to'] = '';
		$this->vars['subject'] = 'Fwd: ' . $email->subject;
		$this->vars['content'] = "\r\n\r\n" . '---------- Forwarded message ----------' . "\r\n"
			. 'From: ' . $email->fromSimple . "\r\n"
			. 'Date: ' . $email->date . "\r\n" . 'Subject: ' . $email->subject . "\r\n"
			. 'To: ' . $email->toSimple . "\r\n";
		if (strlen($email->ccSimple)!=0)
			$this->vars['content'] .= 'Cc: ' . $email->ccSimple . "\r\n";
		if(empty($email->htmlmsg))
			$this->vars['content'] .= $email->plainmsg;
		else
			$this->vars['content'] .= $email->htmlmsg;
		$this->render('compose');
	}
	
	public function sendMessage() {
		// Test si l'utilisateur est connecté
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		// Test si des variables POST "compose" ont été envoyés
		if(!isset($_POST['email'])) {
			header('Location: '.WEB_ROOT.'compose/index');
			exit();
		}
		
		/*
		// Pré-traitement du formulaire
		$_POST['email'] = array_map('trim',$_POST['email']);
		$_POST['email'] = array_map('addslashes',$_POST['email']);
		extract($_POST['email']);
		// Validation des champs
		if(empty($to)) { $_SESSION['form'] = $_POST['email']; $_SESSION['errors']['to'] = "Destinataire : champs requis"; }
		
		/ *
		$envelope["from"] 		= $from;
		$envelope["to"]   		= $to;
		$envelope["cc"]   		= $to;
		$envelope["bcc"]  		= $bcc;
		$envelope["subject"]  	= $subject;
		$envelope["date"]  		= date('r');
		$body = array();
		* /
		
		$envelope["from"]= "joe@example.com";
		$envelope["to"]  = "foo@example.com";
		$envelope["cc"]  = "bar@example.com";

		$part1["type"] = TYPEMULTIPART;
		$part1["subtype"] = "mixed";

		$filename = "/tmp/imap.c.gz";
		$fp = fopen($filename, "r");
		$contents = fread($fp, filesize($filename));
		fclose($fp);

		$part2["type"] = TYPEAPPLICATION;
		$part2["encoding"] = ENCBINARY;
		$part2["subtype"] = "octet-stream";
		$part2["description"] = basename($filename);
		$part2["contents.data"] = $contents;

		$part3["type"] = TYPETEXT;
		$part3["subtype"] = "plain";
		$part3["description"] = "description3";
		$part3["contents.data"] = "contents.data3\n\n\n\t";

		$body[1] = $part1;
		$body[2] = $part2;
		$body[3] = $part3;

		echo nl2br(imap_mail_compose($envelope, $body));
		
		//$this->render('compose');
		*/
		
		$pe = $_POST['email'];
		extract($_POST['email']);
		
		$to = Email::completeEmailsFromStringSimple ( $to );
		$cc = Email::completeEmailsFromStringSimple ( $cc );
		$bcc = Email::completeEmailsFromStringSimple ( $bcc );
		
		if ( !( isset($to) && !empty($to) && isset($subject) && !empty($subject) ) )
		{
			$this->vars['info'] = 'Votre email doit comporter au moins un destinataire et un sujet.';
			$this->vars['link'] = WEB_ROOT . 'compose/index';
			$this->vars['button'] = 'Retour';
			$this->render('info');
		}
		
		$m = Imap::open (DRAFTS);
		
		// supprimer le brouillon
		if ( isset($uid) && $uid != -1 )
		{
			imap_delete($m, imap_msgno($m,$uid));
			imap_expunge($m);
		}
		
		
		$from = $_SESSION['user']['username'].'@'.EMAILDOMAIN;
		$headers = "From: $from\r\n"
			. "Reply-To: $from\r\n";
		
		//echo "to: $to<br/>subject: $subject<br/>content: $content<br/>cc: $cc<br/>bcc: $bcc<br/>";
		// l'envoi d'emails est desactivé sur le serveur
		//$res = imap_mail ( $to, $subject, $content . "\r\n", $headers, $cc, $bcc );
		//echo "res: $res<br/>";
		$SMTPMail = new SMTPClient ( SMTPSERVER, SMTPPORT, '', '', $from, $to, $cc, $bcc, $subject, $content );
		$res = $SMTPMail->SendMail();
		
		$msg = "From: $from\r\nReply-To: $from\r\n".
			 "To: $to\r\n";
		if ( isset ( $cc ) && !empty ( $cc ) )
			$msg .= "Cc: $cc\r\n";
		if ( isset ( $bcc ) && !empty ( $bcc ) )
			$msg .= "Bcc: $bcc\r\n";
		$msg .= "Subject: $subject\r\n".
			 "Date: ".date("r", strtotime("now"))."\r\n".
			 "\r\n" . $content . "\r\n";
		
		if ( $res['result'] == 'OK' )
		{
			// récupérer la valeur du prochain uid qui sera créé
			$mc = imap_status ( $m, Imap::$hostname . "INBOX.Sent", SA_UIDNEXT );
			if ( !$mc )
			{
				/* on estime que si le message a bien été envoyé mais qu'on ne peut pas l'ajouter aux Sent c'est pas trop grave
				Imap::close ( $m );
				die($res . ' could not check emails');*/
			}
			else
			{
				$next = $mc->uidnext;
				if ( imap_append ( $m, Imap::$hostname . "INBOX.Sent", $msg ) === true )
				{
					//imap_setflag_full($m, imap_msgno($m,$next), "\\Seen");
					Imap::close ($m);
					$m = Imap::open (SENT);
					imap_setflag_full($m, $next, "\\Seen", ST_UID);
				}
				else
				{
					// on estime que si le message a bien été envoyé mais qu'il n'a pas pu être ajouté aux Sent c'est pas trop grave
				}
			}
			$_SESSION['email'] = '';
		}
		else
		{
			$_SESSION['email'] = $pe;
		}
		
		Imap::close ($m);
		
		if ( $res['result'] == 'OK' )
			$this->vars['info'] = 'Votre email a bien &eacute;t&eacute; envoy&eacute;.';
		else
			$this->vars['info'] = 'Erreur : Votre email n\'a pas pu &ecirc;tre envoy&eacute;. Le serveur d\'email a retourn&eacute; l\'erreur suivante : ' . htmlentities($res['result']);
		//$this->vars['info'] .= '<br/><pre>' . var_dump ( $res ) . $msg . '</pre>';// debug
		if ( $res['result'] == 'OK' )
		{
			$this->vars['link'] = WEB_ROOT . 'webmail/menu';
			$this->vars['button'] = 'Ok';
		}
		else
		{
			$this->vars['link'] = WEB_ROOT . 'compose/index';
			$this->vars['button'] = 'Retour';
		}
		
		$this->render('info');
	}
	
}
